import axios from "axios";
import { Dialog, Notify } from "vant";
import { getToken, toLogin, isDingtalk } from "chaos-sso-util";

axios.defaults.headers["Content-Type"] = "application/json;charset=utf-8";
// 创建axios实例
const service = axios.create({
  // axios中请求配置有baseURL选项，表示请求URL公共部分
  //baseURL: process.env.VUE_APP_BASE_API,
  baseURL: process.env.VUE_APP_OA_HOST_URL,
  // 超时
  timeout: 1000 * 60,
});

// request拦截器
service.interceptors.request.use(
  (config) => {
    if (getToken()) {
      //config.headers['Authorization'] = 'Bearer ' + getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
      config.headers[process.env.VUE_APP_SSO_HEADER_TOKEN] = getToken(); // 让每个请求携带自定义token 请根据实际情况自行修改
    }
    return config;
  },
  (error) => {
    console.log(error);
    Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  (res) => {
    const data = res.data;
    if (data.status === 401) {
      if (isDingtalk()) {
        //removeToken()
        toLogin();
      } else {
        Dialog.confirm({
          title: "系统提示",
          message: "登录状态已过期，您可以继续留在该页面，或者重新登录",
        }) .then(() => {
          toLogin();
        }).catch(() => {
            // on cancel
        });
      }
    } else if (data.status < 200 || data.status > 300) {
      Notify({ type: 'danger', message: data.msg || "Error" });
      return Promise.reject(new Error(data.message || "Error"));
    } else if (data.status == 404) {
      Notify({ type: 'danger', message: '没有找到服务404' });
      return Promise.reject(new Error(data.message || "Error"));
    } else {
      return data;
    }
  },
  (error) => {
    let response = error.response;
    if (response) {
      if (response.data.code === 401) {
        if (isDingtalk()) {
          toLogin();
        } else {
          Dialog.confirm({
            title: "系统提示",
            message: "登录状态已过期，您可以继续留在该页面，或者重新登录",
          }) .then(() => {
            toLogin();
          }).catch(() => {
              // on cancel
          });
        }
      } else if (response.data.code == 404) {
        Notify({ type: 'danger', message: `404 ${response.data.data.error} [${response.data.data.path}]` });
      } else {
        Notify({ type: 'danger', message: response.data.msg });
      }
    } else {
      Notify({ type: 'danger', message: error.message });
    }
    return Promise.reject(error);
  }
);

export default service;
